package com.xuanzheng.company.dao.impl;

import com.xuanzheng.company.dao.TaskDao;
import com.xuanzheng.company.entity.Task;
import com.xuanzheng.company.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class TaskDaoImpl implements TaskDao {
    @Override
    public boolean createTask(Task task) {
        String sql = "INSERT INTO `task` (`id`, `title`, `content`, `company_id`, `manager_id`, `employee_id`, `create_time`, `status`, `score`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, task.getId());
            pstmt.setString(2, task.getTitle());
            pstmt.setString(3, task.getContent());
            pstmt.setString(4, task.getCompanyId());
            pstmt.setString(5, task.getManagerId());
            pstmt.setString(6, task.getEmployeeId());
            pstmt.setTimestamp(7, new Timestamp(task.getCreateTime().getTime()));
            pstmt.setInt(8, task.getStatus());
            pstmt.setInt(9, task.getScore());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Task getTaskById(String id) {
        String sql = "SELECT t.*, u.name as employee_name, u.phone as employee_phone " +
                    "FROM `task` t LEFT JOIN `user` u ON t.employee_id = u.id " +
                    "WHERE t.id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, id);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return extractTaskFromResultSetWithJoin(rs);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Task> getTasksByCompanyId(String companyId) {
        String sql = "SELECT t.*, u.name as employee_name, u.phone as employee_phone " +
                    "FROM `task` t LEFT JOIN `user` u ON t.employee_id = u.id " +
                    "WHERE t.company_id = ? ORDER BY t.create_time DESC";
        return getTasksByQueryWithJoin(sql, companyId);
    }

    @Override
    public List<Task> getTasksByEmployeeId(String employeeId) {
        String sql = "SELECT t.*, u.name as employee_name, u.phone as employee_phone " +
                    "FROM `task` t LEFT JOIN `user` u ON t.employee_id = u.id " +
                    "WHERE t.employee_id = ? ORDER BY t.create_time DESC";
        return getTasksByQueryWithJoin(sql, employeeId);
    }

    @Override
    public List<Task> getTasksByManagerId(String managerId) {
        String sql = "SELECT t.*, u.name as employee_name, u.phone as employee_phone " +
                    "FROM `task` t LEFT JOIN `user` u ON t.employee_id = u.id " +
                    "WHERE t.manager_id = ? ORDER BY t.create_time DESC";
        return getTasksByQueryWithJoin(sql, managerId);
    }

    @Override
    public boolean updateTaskStatus(String id, int status) {
        String sql = "UPDATE `task` SET `status` = ? WHERE `id` = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, status);
            pstmt.setString(2, id);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateTaskCompleteTime(String id, java.util.Date completeTime) {
        String sql = "UPDATE `task` SET `complete_time` = ?, `status` = 1 WHERE `id` = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setTimestamp(1, new Timestamp(completeTime.getTime()));
            pstmt.setString(2, id);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean deleteTask(String id) {
        String sql = "DELETE FROM `task` WHERE `id` = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, id);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean confirmTaskCompletion(String id, int score, java.util.Date confirmTime) {
        String sql = "UPDATE `task` SET `confirm_time` = ?, `status` = 2, `score` = ? WHERE `id` = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setTimestamp(1, new Timestamp(confirmTime.getTime()));
            pstmt.setInt(2, score);
            pstmt.setString(3, id);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateTaskScore(String id, int score) {
        String sql = "UPDATE `task` SET `score` = ? WHERE `id` = ? AND `status` = 2";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, score);
            pstmt.setString(2, id);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    private List<Task> getTasksByQuery(String sql, String param) {
        List<Task> tasks = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, param);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    tasks.add(extractTaskFromResultSet(rs));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tasks;
    }

    private List<Task> getTasksByQueryWithJoin(String sql, String param) {
        List<Task> tasks = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, param);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    tasks.add(extractTaskFromResultSetWithJoin(rs));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tasks;
    }

    private Task extractTaskFromResultSet(ResultSet rs) throws SQLException {
        Task task = new Task();
        task.setId(rs.getString("id"));
        task.setTitle(rs.getString("title"));
        task.setContent(rs.getString("content"));
        task.setCompanyId(rs.getString("company_id"));
        task.setManagerId(rs.getString("manager_id"));
        task.setEmployeeId(rs.getString("employee_id"));
        task.setCreateTime(rs.getTimestamp("create_time"));
        
        Timestamp completeTime = rs.getTimestamp("complete_time");
        if (completeTime != null) {
            task.setCompleteTime(completeTime);
        }
        
        Timestamp confirmTime = rs.getTimestamp("confirm_time");
        if (confirmTime != null) {
            task.setConfirmTime(confirmTime);
        }
        
        task.setStatus(rs.getInt("status"));
        task.setScore(rs.getInt("score"));
        return task;
    }

    private Task extractTaskFromResultSetWithJoin(ResultSet rs) throws SQLException {
        Task task = new Task();
        task.setId(rs.getString("id"));
        task.setTitle(rs.getString("title"));
        task.setContent(rs.getString("content"));
        task.setCompanyId(rs.getString("company_id"));
        task.setManagerId(rs.getString("manager_id"));
        task.setEmployeeId(rs.getString("employee_id"));
        task.setCreateTime(rs.getTimestamp("create_time"));
        
        Timestamp completeTime = rs.getTimestamp("complete_time");
        if (completeTime != null) {
            task.setCompleteTime(completeTime);
        }
        
        Timestamp confirmTime = rs.getTimestamp("confirm_time");
        if (confirmTime != null) {
            task.setConfirmTime(confirmTime);
        }
        
        task.setStatus(rs.getInt("status"));
        task.setScore(rs.getInt("score"));
        
        // 添加员工信息
        task.setEmployeeName(rs.getString("employee_name"));
        task.setEmployeePhone(rs.getString("employee_phone"));
        
        return task;
    }
} 